package com.my.study.net;

import lombok.extern.slf4j.Slf4j;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

/**
 * @author Carlos
 * @version 1.0
 * @Description 发送端
 * @date 2021/7/4 15:04
 **/
@Slf4j(topic = "c.UDPSenderB")
public class UDPSenderB {

    public static void main(String[] args) throws IOException {
        // 创建DatagramSocket对象，准备发送和接收数据
        DatagramSocket socket = new DatagramSocket(9998);

        //================================================发送消息
        byte[] buf = "Hello，明天吃火锅".getBytes();
        DatagramPacket packet = new DatagramPacket(buf, 0, buf.length, InetAddress.getByName("192.168.1.3"), 9999);
        log.debug("B端，给A端发送火锅邀请消息...");
        socket.send(packet);

        //================================================接收消息
        byte[] receiveBuf = new byte[1024];
        DatagramPacket receivePack = new DatagramPacket(receiveBuf, 0, receiveBuf.length);
        log.debug("B端，等待接收A端回复...");
        socket.receive(receivePack);
        String msg = new String(receivePack.getData(), 0, receivePack.getLength());
        log.debug("B端接收的消息: {}", msg);

        // 关闭资源
        socket.close();
    }


}
